package com.wolfeyes.framework.springsecurity.handle;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wolfeyes.common.response.ResponseResult;
import com.wolfeyes.common.utils.network.web.ResponseUtils;
import com.wolfeyes.framework.springsecurity.domain.model.CustomizeUserDetails;
import com.wolfeyes.system.domain.LoginUser;
import com.wolfeyes.system.domain.SysUser;
import com.wolfeyes.system.domain.vo.SysUserVo;
import com.wolfeyes.system.service.impl.SysUserServiceImpl;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @description SpringSecurity安全认证权限框架
 * @description 登录成功处理类,登录成功后会调用里面的方法
 * @see Talk is cheap, Show me the code. -- Linus Torvalds
 * @title 自定义的登录（成功）处理器
 * @author yanyljava
 * @create 2022-01-14 21:25
 */
@Slf4j
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private SysUserServiceImpl sysUserService;

	/**
	 * @title 获取当前用户信息，拿到用户名或者userId，使用JWT生成token，然后返回创建的token
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
		
		log.debug("自定义的登录成功处理器被调用 Start！");
		CustomizeUserDetails customizeUserDetails = (CustomizeUserDetails) authentication.getPrincipal();
		//颁发token
		//Map<String,Object> emptyMap = new HashMap<>(4);
		//emptyMap.put(UserConstants.USER_ID,principal.getId());
		//String token = JwtTokenUtil.generateToken(principal.getUsername(), emptyMap);
		//ResponseUtil.out(ResultUtil.success(token));
		
		//httpServletResponse.setContentType("application/json;charset=utf-8");
		//PrintWriter printWriter = httpServletResponse.getWriter();
		//ObjectMapper objectMapper =  new ObjectMapper();
		
		//SysUserVo sysUserVo = new ObjectMapper().readValue(httpServletRequest.getInputStream(), SysUserVo.class);
		SysUser sysUser = customizeUserDetails.getUser();
		SysUserVo sysUserVo = new SysUserVo();
		BeanUtil.copyProperties(sysUser, sysUserVo, true);
		LoginUser loginUser = sysUserService.login(sysUserVo);
		ResponseResult responseResult = ResponseResult.success(loginUser);
		//String jsonResultString = objectMapper.writeValueAsString(responseResult);
		//printWriter.write(jsonResultString);
		//printWriter.flush();
		//printWriter.close();
		ResponseUtils.out(responseResult);
		log.debug("自定义的登录成功处理器被调用 End！");
	}
}

